<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\DishService;
use App\Services\CategoryService;
use App\Http\Requests\Admin\DishRequest;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class DishController extends Controller
{
    protected DishService $dishService;
    protected CategoryService $categoryService;

    public function __construct(DishService $dishService, CategoryService $categoryService)
    {
        $this->dishService = $dishService;
        $this->categoryService = $categoryService;
    }

    /**
     * 显示创建菜品页面
     */
    public function create(Request $request): View
    {
        $categories = $this->categoryService->getAllCategories();
        $selectedCategoryId = $request->get('category_id');
        
        return view('admin.dishes.create', compact('categories', 'selectedCategoryId'));
    }

    /**
     * 显示编辑菜品页面
     */
    public function edit(int $id): View
    {
        $dish = $this->dishService->getDishById($id);
        $categories = $this->categoryService->getAllCategories();
        
        return view('admin.dishes.edit', compact('dish', 'categories'));
    }

    /**
     * 显示菜品管理页面
     */
    public function index(Request $request): View
    {
        $perPage = 20;
        $filters = $request->only(['category_id', 'is_featured', 'search']);

        if (!empty(array_filter($filters))) {
            $dishes = $this->dishService->getDishesByFilters($filters, $perPage);
        } else {
            $dishes = $this->dishService->getDishes($perPage);
        }
        
        $categories = $this->categoryService->getAllCategories();
        $stats = $this->dishService->getDishStats();
        
        return view('admin.dishes.index', compact('dishes', 'categories', 'stats'));
    }

    /**
     * 获取菜品列表API
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $filters = $request->only(['category_id', 'is_featured', 'search']);

        if (!empty(array_filter($filters))) {
            $dishes = $this->dishService->getDishesByFilters($filters, $perPage);
        } else {
            $dishes = $this->dishService->getDishes($perPage);
        }

        return response()->json([
            'success' => true,
            'data' => $dishes->items(),
            'pagination' => [
                'current_page' => $dishes->currentPage(),
                'last_page' => $dishes->lastPage(),
                'per_page' => $dishes->perPage(),
                'total' => $dishes->total(),
            ]
        ]);
    }

    /**
     * 显示菜品详情页面
     */
    public function show(int $id)
    {
        $dish = $this->dishService->getDishById($id);

        // 如果是API请求，返回JSON
        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'data' => $dish
            ]);
        }
        
        // 否则返回视图
        return view('admin.dishes.show', compact('dish'));
    }

    /**
     * 创建菜品
     */
    public function store(DishRequest $request)
    {
        $data = $request->validated();
        
        // 如果有 menu_id 参数，设置菜单关联
        if ($request->has('menu_id')) {
            $data['menu_id'] = $request->input('menu_id');
            $data['dish_source'] = 'menu';
            $data['is_public'] = false;
        }
        
        $dish = $this->dishService->createDish($data);

        // 如果是从菜单页面创建的，重定向回菜单详情页
        if ($request->has('menu_id')) {
            return redirect()->route('admin.menus.show', $request->input('menu_id'))
                ->with('success', "菜品「{$dish->name}」创建成功！");
        }

        // 否则返回JSON响应（API调用）
        return response()->json([
            'success' => true,
            'data' => $dish
        ], 201);
    }

    /**
     * 更新菜品
     */
    public function update(DishRequest $request, int $id): \Illuminate\Http\RedirectResponse
    {
        $dish = $this->dishService->updateDish($id, $request->validated());

        return redirect()->route('admin.dishes.index')->with('success', "菜品「{$dish->name}」更新成功！");
    }

    /**
     * 删除菜品
     */
    public function destroy(int $id): JsonResponse
    {
        $this->dishService->deleteDish($id);

        return response()->json([
            'success' => true
        ]);
    }

    /**
     * 切换菜品推荐状态
     */
    public function toggleFeatured(int $id): \Illuminate\Http\RedirectResponse
    {
        $dish = $this->dishService->toggleDishFeatured($id);
        
        $status = $dish->is_featured ? '推荐' : '取消推荐';
        $message = "菜品「{$dish->name}」已{$status}";

        return redirect()->back()->with('success', $message);
    }

    /**
     * 按分类获取菜品
     */
    public function byCategory(int $categoryId, Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $dishes = $this->dishService->getDishesByCategory($categoryId, $perPage);

        return response()->json([
            'success' => true,
            'data' => $dishes->items(),
            'pagination' => [
                'current_page' => $dishes->currentPage(),
                'last_page' => $dishes->lastPage(),
                'per_page' => $dishes->perPage(),
                'total' => $dishes->total(),
            ]
        ]);
    }

    /**
     * 获取推荐菜品
     */
    public function featured(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $dishes = $this->dishService->getFeaturedDishes($perPage);

        return response()->json([
            'success' => true,
            'data' => $dishes->items(),
            'pagination' => [
                'current_page' => $dishes->currentPage(),
                'last_page' => $dishes->lastPage(),
                'per_page' => $dishes->perPage(),
                'total' => $dishes->total(),
            ]
        ]);
    }

    /**
     * 搜索菜品
     */
    public function search(Request $request): JsonResponse
    {
        $request->validate([
            'query' => 'required|string|min:1'
        ]);

        $perPage = $request->get('per_page', 20);
        $dishes = $this->dishService->searchDishes($request->get('query'), $perPage);

        return response()->json([
            'success' => true,
            'data' => $dishes->items(),
            'pagination' => [
                'current_page' => $dishes->currentPage(),
                'last_page' => $dishes->lastPage(),
                'per_page' => $dishes->perPage(),
                'total' => $dishes->total(),
            ]
        ]);
    }

    /**
     * 获取菜品统计信息
     */
    public function stats(): JsonResponse
    {
        $stats = $this->dishService->getDishStats();

        return response()->json([
            'success' => true,
            'data' => $stats
        ]);
    }

    /**
     * 批量更新菜品分类
     */
    public function batchUpdateCategory(Request $request): JsonResponse
    {
        $request->validate([
            'dish_ids' => 'required|array',
            'dish_ids.*' => 'integer|exists:dishes,id',
            'category_id' => 'required|integer|exists:categories,id'
        ]);

        $count = $this->dishService->batchUpdateCategory(
            $request->get('dish_ids'),
            $request->get('category_id')
        );

        return response()->json([
            'success' => true,
            'data' => [
                'updated_count' => $count
            ]
        ]);
    }

    /**
     * 批量设置推荐状态
     */
    public function batchSetFeatured(Request $request): JsonResponse
    {
        $request->validate([
            'dish_ids' => 'required|array',
            'dish_ids.*' => 'integer|exists:dishes,id',
            'is_featured' => 'required|boolean'
        ]);

        $count = $this->dishService->batchSetFeatured(
            $request->get('dish_ids'),
            $request->get('is_featured')
        );

        return response()->json([
            'success' => true,
            'data' => [
                'updated_count' => $count
            ]
        ]);
    }
}